package com.slkj.shilixiaoyuanapp.ui.main.community;

import android.support.v4.view.ViewCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.BaseLazyFragment;
import com.slkj.shilixiaoyuanapp.data.UserRequest;
import com.slkj.shilixiaoyuanapp.entity.CommunityEntity;
import com.slkj.shilixiaoyuanapp.entity.CommunityListEntity;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.view.DividerItemDecoration;
import com.slkj.shilixiaoyuanapp.view.MySwipeRefreshLayout;
import com.slkj.shilixiaoyuanapp.view.StateLayout;
import com.slkj.shilixiaoyuanapp.view.dialog.SendCommentDialog;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created  on 2018-08-13
 *
 * @author 唐开阔
 * @describe 社区fragment
 * TODO:滑动事件冲突-实例：SwipeRefreshLayout RecyclerView双层嵌套
 * --已解决，未搞懂原理
 */
public class CommunityFragment extends BaseLazyFragment implements CommunityAdapter.CallBack {
    @BindView(R.id.send)
    View send;
    @BindView(R.id.layout_new_mes)
    View viewNewMes;

    @BindView(R.id.recycer)
    RecyclerView recycer;
    @BindView(R.id.refresh)
    MySwipeRefreshLayout refreshLayout;
    @BindView(R.id.layout_root)
    StateLayout stateLayout;
    @BindView(R.id.tv_new_mes)
    TextView tvMes;
    @BindView(R.id.img_head)
    ImageView imgHead;
    List<CommunityEntity> data;
    CommunityAdapter adapter;

    private int startId = 0;
    private int page = 1;
    private int count = 20;

    @Override
    protected int getResId() {
        return R.layout.fragment_community;
    }

    @Override
    protected void onRealLoaded() {
        send.setOnClickListener(v -> startActivity(SendCircleActivity.class));
        refreshLayout.setEnabled(false);
        recycer.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new CommunityAdapter(data, getContext());
        recycer.setAdapter(adapter);
        recycer.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
        refreshLayout.setOnRefreshListener(this::refresh);
        adapter.setCallBack(this);
        adapter.setOnLoadMoreListener(this::loadMore, recycer);
        refreshLayout.setOnChildScrollUpCallback(
                (parent, child) -> ViewCompat.canScrollVertically(recycer, -1));
        refresh();
    }


    @OnClick(R.id.layout_new_mes)void goNewMes(){
        startActivity(NewMessageActivity.class);
    }
    private void loadMore() {
        HttpHeper.get().comunityService()
                .getCommunityList(2, startId, page , count)
                .compose(bindToLifecycle())
                .compose(getThread())
                .subscribe(new CommonCallBack<CommunityListEntity>() {
                    @Override
                    public void onCallBackSuccess(CommunityListEntity data) {
                        setData(false, data.getList());
                        if (!data.getList().isEmpty()) {
                            startId = data.getList().get(data.getList().size() - 1).getId();
                        }
                    }

                    @Override
                    public void onFail(String mes) {
                        adapter.loadMoreFail();
                    }
                });
    }

    public void refresh() {
        page = 1;
        startId = 0;
        //这里的作用是防止下拉刷新的时候还可以上拉加载
        adapter.setEnableLoadMore(false);
        HttpHeper.get().comunityService()
                .getCommunityList(2, startId, page, count)
                .compose(bindToLifecycle())
                .compose(getThread())
                .subscribe(new CommonCallBack<CommunityListEntity>(stateLayout) {
                    @Override
                    public void onCallBackSuccess(CommunityListEntity data) {
                        if (data.getNewMessageCount() == 0){
                            viewNewMes.setVisibility(View.GONE);
                        }else {
                            tvMes.setText(data.getNewMessageCount() + "条新消息");
                            Glide.with(getContext()).load(data.getNewMessageHead()).into(imgHead);
                            viewNewMes.setVisibility(View.VISIBLE);

                        }
                        if (data.getList().isEmpty()) {
                            stateLayout.showEmptyView();
                        } else {
                            startId = data.getList().get(data.getList().size() - 1).getId();
                            setData(true, data.getList());
                            refreshLayout.setRefreshing(false);
                            refreshLayout.setEnabled(true);
                        }

                    }

                    @Override
                    public void onFail(String mes) {
                        super.onFail(mes);
                        refreshLayout.setRefreshing(false);

                    }
                });
    }

    private void setData(boolean isRefresh, List data) {
        page++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            adapter.setNewData(data);
        } else {
            if (size > 0) {
                adapter.addData(data);
            }
        }
        if (size < count) {
            //第一页如果不够一页就不显示没有更多数据布局
            adapter.loadMoreEnd(isRefresh);
        } else {
            adapter.loadMoreComplete();
        }
    }

    /**
     * 点赞
     *
     * @param id
     * @param pos
     */
    @Override
    public void fabulous(int id, int pos) {
        HttpHeper.get().comunityService()
                .fabulous(id)
                .compose(bindToLifecycle())
                .compose(getThread())
                .subscribe(new CommonCallBack<String>(true, getContext()) {
                    @Override
                    public void onCallBackSuccess(String mes) {
                        showToast(mes);
                        adapter.getData().get(pos).changeFabulous();
                        adapter.notifyItemChanged(pos);
                    }
                });

    }

    /**
     * @param comment
     * @param pos
     * @param type    1回复，2评论
     */
    @Override
    public void comment(CommunityEntity.Comment comment, int pos, int type) {
        int commentId = 0;
        if (comment != null){
            commentId = comment.getId();
        }
        int finalCommentId = commentId;
        SendCommentDialog.creat(commentStr -> {
            HttpHeper.get().comunityService()
                    .comment(adapter.getData().get(pos).getId(),commentStr, finalCommentId)
                    .compose(bindToLifecycle())
                    .compose(getThread())
                    .subscribe(new CommonCallBack<CommunityEntity.Comment>(true, getContext()) {
                        @Override
                        public void onCallBackSuccess(CommunityEntity.Comment data) {
                            data.setNickName(UserRequest.getInstance().getUser().getUser().getUNickName());
                            adapter.getData().get(pos).getComment().add(data);
                            adapter.notifyItemChanged(pos);
                        }
                    });
        }).show(getFragmentManager());

    }
}
